<!DOCTYPE html>
<html>
<head>
    <meta charset="utf-8"/>
    <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
    <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
    <link href="__ADMIN__/easyweb/images/favicon.ico" rel="icon">
    <title>单文件上传</title>
    <link rel="stylesheet" href="__ADMIN__/easyweb/libs/layui/css/layui.css"/>
    <link rel="stylesheet" href="__ADMIN__/easyweb/module/admin.css?v=317"/>
    <link rel="stylesheet" href="__LIB__/font-awesome-4.7.0/css/font-awesome.min.css"/>
    <!--[if lt IE 9]>
    <script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
    <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
    <![endif]-->

    <style>
        .layui-tab-content {
            background: #fff;
        }

        /* 文件列表item */
        .file-choose-list-item {
            position: relative;
            display: inline-block;
            vertical-align: top;
            padding: 8px 6px;
            margin: 5px 0;
            cursor: pointer;
        }

        .file-choose-list-item:hover {
            background-color: #F7F7F7;
        }

        /* 文件列表图片 */
        .file-choose-list-item-img {
            width: 90px;
            height: 90px;
            background-repeat: no-repeat;
            background-position: center;
            background-size: cover;
            border-radius: 3px;
            overflow: hidden;
            position: relative;
            background-color: #eee;
        }

        .file-choose-list-item-img.img-icon {
            background-size: inherit;
            background-color: transparent;
        }

        .file-choose-list-item.active .file-choose-list-item-img:after {
            content: "";
            position: absolute;
            left: 0;
            top: 0;
            bottom: 0;
            right: 0;
            background: rgba(0, 0, 0, 0.3);
        }

        /* 文件列表名称 */
        .file-choose-list-item-name {
            width: 90px;
            overflow: hidden;
            text-overflow: ellipsis;
            white-space: nowrap;
            color: #333;
            font-size: 12px;
            text-align: center;
            margin-top: 12px;
        }

        /* 文件列表复选框 */
        .file-choose-list-item-ck {
            position: absolute;
            right: 8px;
            top: 8px;
        }

        .file-choose-list-item-ck .layui-form-checkbox {
            padding: 0;
        }

        /* 文件列表操作菜单 */
        .file-choose-oper-menu {
            background-color: #fff;
            position: absolute;
            left: 8px;
            top: 8px;
            border-radius: 2px;
            box-shadow: 0px 0px 10px rgba(0, 0, 0, .15);
            transition: all .3s;
            overflow: hidden;
            transform: scale(0);
            transform-origin: left top;
            visibility: hidden;
        }

        .file-choose-oper-menu.show {
            transform: scale(1);
            visibility: visible;
        }

        /* 文件列表操作菜单item */
        .file-choose-oper-menu-item {
            color: #555;
            padding: 6px 5px;
            font-size: 14px;
            min-width: 70px;
            text-align: center;
            cursor: pointer;
            display: block;
        }

        .file-choose-oper-menu-item:hover {
            background-color: #eee;
        }

        /** 文件列表为空时样式 */
        .file-choose-empty {
            text-align: center;
            color: #999;
            padding: 50px 0;
        }

        .file-choose-empty .layui-icon {
            font-size: 60px;
            display: block;
            margin-bottom: 8px;
        }


    </style>
</head>
<body>
<!-- 正文开始 -->
<div class="layui-fluid ew-console-wrapper">
    <div class="layui-tab layui-tab-card">
        <ul class="layui-tab-title">
            <li class="layui-this">单选上传</li>
            <li>选择已上传文件</li>
        </ul>
        <div class="layui-tab-content">
            <div class="layui-tab-item layui-show">
                <div class="layui-upload-drag" id="upload">
                    <i class="layui-icon"></i>
                    <p>点击上传，或将文件拖拽到此处</p>
                    <div id="uploadView">
                        <hr>
                        <img src="/static/images/default_img.png" alt="上传成功后渲染" style="max-width: 196px;height: auto">
                    </div>
                </div>
            </div>
            <div class="layui-tab-item">
                <div class="layui-card-header">当前位置：<span id="tv-current-position"></span></div>
                <div class="layui-card-body">
                    <div>
                        <button id="file-btn-back" class="layui-btn layui-btn-sm layui-btn-primary icon-btn">
                            <i class="layui-icon">&#xe65c;</i>返回上级
                        </button>
                        <button id="file-btn-refresh" class="layui-btn layui-btn-sm layui-btn-primary icon-btn">
                            <i class="layui-icon">&#xe669;</i>刷新
                        </button>
                        <button id="file-btn-choose" class="layui-btn layui-btn-sm layui-btn-primary icon-btn">选择</button>
                    </div>
                    <div id="file-list-group"></div>
                </div>
            </div>
        </div>
    </div>
</div>
<!-- js部分 -->
<script type="text/javascript" src="__ADMIN__/easyweb/libs/layui/layui.js"></script>
<script type="text/javascript" src="__ADMIN__/easyweb/js/common.js?v=317"></script>
<script type="text/javascript" src="__LIB__/jquery.min.js"></script>
<script type="text/javascript" src="__LIB__/layer/layer.js"></script>
<script type="text/javascript" src="__LIB__/common.js"></script>
<script type="text/javascript" src="__ADMIN__/js/admin.js"></script>
<script>
    layui.use(['layer', 'upload', 'element', 'fileChoose', 'form', 'notice'], function () {
        var $ = layui.jquery
            , layer = layui.layer
            , upload = layui.upload
            , element = layui.element
            , fileChoose = layui.fileChoose
            , form = layui.form
            , notice = layui.notice;

        // 文件表
        var dataList = [];
        // 数量上限,0表示不限制
        var num = '{$num}';
        //已选中的数据
        var chooseData = [];
        //拖拽上传
        upload.render({
            elem: '#upload'
            , url: "{:url('common/base/uploadFile')}"
            ,accept:"file"
            , done: function (res) {

                layui.$('#uploadView').find('img').attr('src', res.data.src);

                if (num == 1){
                    // 操作父级页面的dom
                    $("#{$id}", parent.document).find('img').attr('src', res.data.src)
                    $("#{$id}", parent.document).find('input').val(res.data.src)
                }else if(num > 0){
                    var tableListHtml = "<tr><td><img src='" + res.data.src + "' height='80'/></td><td><a class='layui-btn layui-btn-danger upload-file-del'>删除</a></td></tr>";
                    $("#{$id}", parent.document).next('.layui-upload-list').find('.layui-table').find('tbody').append(tableListHtml)
                }

                parent.layer.closeAll()
            }
        });

        // 默认配置
        var menu = [{
            name: '预览',
            event: 'preview'
        }, {
            name: '<span style="color: red;">删除</span>',
            event: 'del'
        }];
        // 如果是单选的时候，多一个选择按钮
        if (num == 1) {
            menu = [{
                name: '预览',
                event: 'preview'
            }, {
                name: '选择',
                event: 'choose'
            }, {
                name: '<span style="color: red;">删除</span>',
                event: 'del'
            }]
        }

        // 渲染列表
        function renderList(dir) {
            dir || (dir = $('#tv-current-position').text());
            layer.load(2);
            $.get("{:url('plugin/getFileDirList')}", {
                dir: dir
            }, function (res) {
                layer.closeAll('loading');
                dataList = res.data;
                var htmlStr = fileChoose.renderList({
                    data: dataList,
                    multi: true,
                    menu: menu,
                    response: {
                        method: 'post',  // 请求方式
                        code: 0,  // 成功码，默认200
                        name: 'name',  // 文件名称字段名称
                        url: 'url',  // 文件url字段名称
                        smUrl: 'smUrl',  // 文件缩略图字段名称
                        isDir: 'isDir',  // 是否是文件夹字段名称,boolean类型
                        dir: 'dir'  // 当前文件夹参数名称
                    },
                });
                $('#file-list-group').html(htmlStr);
                // 渲染多选框
                form.render('checkbox')
            }, 'json');
        }

        renderList();

        // 列表点击事件
        $(document).off('click.fclip').on('click.fclip', '#file-list-group .file-choose-list-item', function (e) {
            var item = dataList[$(this).data('index')];
            if (item.isDir) {  // 是否是文件夹
                var cDir = $('#tv-current-position').text();
                cDir += (item.name);
                $('#tv-current-position').text(cDir);
                renderList(cDir);
            } else {
                var $cMenu = $(this).find('.file-choose-oper-menu');
                $('.file-choose-oper-menu').not($cMenu).removeClass('show');
                $cMenu.toggleClass('show');
                e.stopPropagation();
            }
        });

        // 点击空白隐藏下拉框
        $(document).off('click.fclomp').on('click.fclomp', function (e) {
            $('.file-choose-oper-menu').removeClass('show');
        });

        // 菜单事件监听
        $(document).off('click.fclomip').on('click.fclomip', '#file-list-group .file-choose-oper-menu-item', function () {
            var event = $(this).data('event');
            var dataIndex = $(this).parent().parent().data('index');

            if (event == 'del') {  // 删除
                layer.confirm('删除文件有可能导致其他使用此文件的地方无法正常预览，确定要删除此文件吗？', {shade: .1}, function () {
                    $.post("{:url('plugin/delFile')}", {id: dataList[dataIndex].id}, function (ret) {
                        if (ret.code == 0) {
                            layer.msg(ret.msg, {icon: 1, time: 1500}, function () {
                                renderList();
                            });
                        } else {
                            notice.error({message: ret.msg,})
                        }
                    })
                });
            } else if (event == 'preview') {
                window.open(dataList[dataIndex].url);
            } else if (event == 'choose') {
                // 获取缩略图地址
                var smUrl = $(this).parent().parent().find('.file-choose-list-item-img').css("backgroundImage").replace('url(','').replace(')','').replace('"','').replace('"','')
                // 操作父级页面的dom
                $("#{$id}", parent.document).find('img').attr("src",smUrl)
                $("#{$id}", parent.document).find('input').val(dataList[dataIndex].url)
                parent.layer.closeAll()
            } else {
                layer.msg('点击了' + event + '，索引' + dataIndex, {icon: 1});
            }
        });

        // 刷新
        $('#file-btn-refresh').click(function () {
            renderList();
        });

        // 返回上级
        $('#file-btn-back').click(function () {
            var cDir = $('#tv-current-position').text();
            if (cDir != '/') {
                cDir = ''
                $('#tv-current-position').text(cDir);
                renderList(cDir);
            }
        });

        // 防止点击多选框的时候触发下拉菜单,
        // 复选框选中事件
        $(document).on('click', '.file-choose-list-item-ck', function (e) {

            var dataIndex = $(this).parent().data('index');
            var smUrl = $(this).parent().find('.file-choose-list-item-img').css("backgroundImage").replace('url(','').replace(')','').replace('"','').replace('"','')
            // 获取当前选中的缩略图
            dataList[dataIndex]['smUrl'] = smUrl;

            // 判断是不是在当前数组中，如果是就先删除
            if (chooseData.indexOf(dataList[dataIndex]) > -1){
                chooseData.splice(chooseData.indexOf(dataList[dataIndex]),1)
                return false;
            }
            // 判断选中数量
            if (num > 0 && num < chooseData.length + 1) {
                // 提示
                notice.error({message: "只能选择" + num + "个文件"})
                // 阻止多选选中
                $(this).find('input').attr('checked', false)
                // 更新checkbox渲染
                form.render('checkbox')
                return false;
            } else {
                // 将数据加入已选中数组
                chooseData.push(dataList[dataIndex])
            }
            e.stopPropagation();
        });

        // 选择
        $("#file-btn-choose").click(function () {

            if (num == 1 && chooseData.length == 1) {
                $("#{$id}", parent.document).find('img').attr('src', chooseData[0].smUrl)
                $("#{$id}", parent.document).find('input').val(chooseData[0].url)
                //当你在iframe页面关闭自身时
                var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                parent.layer.close(index); //再执行关闭
            } else if (chooseData.length > 0) {

                var tableListHtml = '',values = [];

                for (var i = 0, len = chooseData.length; i < len; i++) {
                    tableListHtml += "<tr><td><img src='" + chooseData[i]['smUrl'] + "' height='80'/></td><td><a class='layui-btn layui-btn-danger upload-file-del' data-index='"+i+"'>删除</a></td></tr>";
                    values.push(chooseData[i]['url'])
                }
                $("#{$id}", parent.document).next('.layui-upload-list').find('.layui-table').find('tbody').append(tableListHtml)

                //当你在iframe页面关闭自身时
                var index = parent.layer.getFrameIndex(window.name); //先得到当前iframe层的索引
                parent.layer.close(index); //再执行关闭

            } else {
                notice.error({message: "请至少选择一个文件", audio: '1'})
            }
        })

    });
</script>
</body>
</html>
